<?php

namespace App\Http\Controllers\Buy;

use App\Mall\OrderCreator;
use App\Models\Item;

class AuctionController extends BaseController
{
    public function buyNow()
    {
        $itemid   = $this->request->input('itemid');
        $quantity = $this->request->input('quantity');
        $pay_type = $this->request->input('pay_type');
        $shipping_type = $this->request->input('shipping_type');

        $this->assign(compact('itemid', 'quantity', 'pay_type', 'shipping_type'));

        if ($itemid && $quantity) {
            $item = Item::find($itemid);
            if ($quantity > $item['stock']){
                return $this->showError(trans('mall.stock_no_enough'));
            }

            $total_fee = $item->price * $quantity;

            $shop = $item->shop;
            $this->assign(compact('item', 'shop', 'total_fee'));

            return $this->view('buy.buynow');
        } else{
            return $this->showError('can_not_buy');
        }
    }

    public function createOrder()
    {
        $itemid = $this->request->input('itemid');
        $item = Item::find($itemid);

        if ($item) {
            $item->quantity = intval($this->request->input('quantity'));
            $creator = new OrderCreator();
            $creator->shop         = $item->shop;
            $creator->items        = [$item];
            $creator->payType      = $this->request->input('pay_type');
            $creator->shippingType = $this->request->input('shipping_type');
            $creator->addressId = $this->request->input('address_id');

            try{
                $order = $creator->createOrder();
                if ($creator->payType == 1) {
                    return redirect('/buy/pay?order_id='.$order->order_id);
                } else {
                    return redirect('/user/trade/bought');
                }
            }catch (\Exception $e) {
                return $this->showError($e->getMessage());
            }
        } else {
            return $this->showError(trans('mall.item_not_exists'));
        }
    }
}
